<?php

class CheckinHelper {
	
	const STATUS_OK   = 1;
	/** 登陆失败 */
	const STATUS_FAIL = 2;
	/** 帐号被禁 */
	const STATUS_DISA = 3;
	/** 退出系统 */
	const STATUS_LOGOUT = 4;
	/** 密码过期 */
	const STATUS_PASSWD = 5;
	
	/**
	 * 记录用户登陆状态
	 */
	public static function track($uid, $uname, $status){
		//防止用户猜测密码，5次禁用户；需求
		if($uid && strcasecmp('admin', $uname) && !in_array($status,array(self::STATUS_OK,self::STATUS_PASSWD))){
			if(!isset($_SESSION['PASSHACK'][$uname])){
				$_SESSION['PASSHACK'][$uname] = 0;
			}
			if($_SESSION['PASSHACK'][$uname]++ >= 4){
				User::update($uid, array('is_disa'=>1));
			}
		}
		elseif($status==self::STATUS_OK){
			unset($_SESSION['PASSHACK']);
		}
		
		return Db::get('LogCheckin')->insert(array(
			'user_id'	=> $uid,
			'user_name' => $uname,
			'ipaddr'	=> UserTrack::getIP(),
			'status'	=> $status,
			'addtime'	=> time(),
		))->exec();
	}
	
	public static function getList($where=null, $s=0, $l=0){
		return Db::get('LogCheckin')->select()->where($where)->limit($s,$l)->order('id DESC')->getAll();
	}
	
	public static function count($where=null){
		return Db::get('LogCheckin')->count()->where($where)->getCol();
	}
	
	public static function status2txt($stat){
		static $list = array(
			self::STATUS_OK	=> '登陆成功',
			self::STATUS_FAIL => '登陆失败',
			self::STATUS_DISA => '锁定账户',
			self::STATUS_LOGOUT => '退出系统',
			self::STATUS_PASSWD => '密码过期',
		);
		return isset($list[$stat]) ? $list[$stat] : '';
	}
	
	/**
	 * 记录最近五次修改的密码，用于修改密码时判断新密码是否可用。
	 */
	public static function trackPasswd($uid, $passwd){
		$r = Db::get('PasswdHistory')->insert(array(
			'user_id'	=> $uid,
			'passwd'	=> $passwd,
			'addtime'	=> time(),
		))->exec();
		if(!$r) return false;
		return self::dropPasswdRecords($uid);
	}
	
	/** 密码是否存在 */
	public static function passwdExists($uid, $passwd){
		return Db::get('PasswdHistory')->count()->where(array('user_id'=>$uid, 'passwd'=>$passwd))->getCol();
	}
	
	private static function dropPasswdRecords($uid){
		//只保留最近5条记录
		$tmp = Db::get('PasswdHistory')->select('addtime')->where(array('user_id'=>$uid))
						->order('addtime DESC')->limit(5)->getCols();
		return Db::get('PasswdHistory')->delete()->where('addtime<'. array_pop($tmp)." AND user_id={$uid}" )->exec();
	}
	
	/** 用户密码过期时间 */
	public static function passwdExpires($uid){
		if(!intval($uid)) return 0;
		$addtime = Db::get('PasswdHistory')->select('addtime')->where(array('user_id'=>$uid))
							->order('addtime DESC')->limit(1)->getCol();
		if(!$addtime){ //生成起始密码时间
			$addtime = time();
			self::trackPasswd($uid, md5($addtime));
		}
		return app_cfg('setting', 'passwdvalidday')*86400 + $addtime;
	}
	
	/** 用户密码是否过期 */
	public static function isPasswdExpired($uid){
return false;
		return self::passwdExpires($uid) < time();
	}
	
}

?>
